package com.teach.cms.api;

import java.util.Arrays;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.teach.cms.entity.Article;
import com.teach.cms.service.ArticleService;

import cn.hutool.core.util.StrUtil;

/**
 * <pre>
 * - 文章信息前端API控制器
 * Author : J.L.Zhou
 * E-Mail : 12020042
 * Tel : 151 1104 7708
 * Date : 2022-10-24 23:37
 * Version : 1.0
 * Copyright 2021 jlzhou.top Inc. All rights reserved.
 * Warning: this content is only for internal circulation of the company.
 *          It is forbidden to divulge it or use it for other commercial purposes.
 * </pre>
 */
@RestController
@RequestMapping("/cms/article")
public class ArticleApi {

	@Autowired
	private ArticleService articleService;

	@GetMapping("list")
	public Object list() throws Exception {
		return articleService.list();
	}

	@GetMapping("page")
	public Object page(Page<Article> page, Integer articleTypeId, String key) throws Exception {
		return articleService.page(page, new QueryWrapper<Article>()
				.eq(articleTypeId != null, "article_type_id", articleTypeId)
				.like(StrUtil.isNotBlank(key), "article_title", key)
				.orderByDesc("article_time"));
	}

	@GetMapping("{id}")
	public Object id(@PathVariable("id") Integer articleId) {
		return articleService.getById(articleId);
	}

	@PostMapping
	public void add(@RequestBody Article article) {
		article.setArticleReadNum(0);
		article.setArticleTime(new Date());
		articleService.save(article);
	}

	@PutMapping
	public void update(@RequestBody Article article) {
		articleService.updateById(article);
	}

	@DeleteMapping("{id}")
	public void delete(@PathVariable("id") Integer articleId) {
		articleService.removeById(articleId);
	}

	@DeleteMapping("ids")
	public void delete(Integer[] articleId) {
		articleService.removeByIds(Arrays.asList(articleId));
	}

}
